/**
 * Created by Dalyn on 2017/3/24.
 * 支付
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import ReactKey from "../../util/ReactKey";
import Util from "../../util/Util";
import { Checkbox,message,Button } from "antd";
import ApplyPayOrderMutation from "./mutation/ApplyPayOrderMutation";
import PayOrderMutation from "./mutation/PayOrderMutation";
import "./css/payment.css";
/*导出组件*/
export default class Payment extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
            inputaccount: null,
            orderId: '', //订单号
            remainOrderMoney: 0,
            cashMoney: 0,
            debtOrderMoney: 0,
            orderMoney: 0,
            orderremain:0,
            accountremain:0,
            partBName:0,
            partBUserName:0,
            partBPhone:0,
            canLoanMoney: 0,
            dayRate:0,
            payWayOrder: 0, //
            payWayLoan: 0, //
            payWayAccount: 0, //
            hadPayWayOrder: '0.00',//已支付
            hadPayWayAccount: '0.00',//已支付
            hadPayWayLoan: '0.00',//已支付
            flag: 1,
            btnLoading: false
        };
        this.orderId;
        this.entype = sessionStorage.getItem('entype');

        this.changeAccount = this.changeAccount.bind(this) //监听input改变
    }

    componentWillMount(){
        if(!this.props.location.state.oid){
            hashHistory.push('/')
        }else{
            this.orderId = this.props.location.state.oid;
            this.applyPayOrder();
        }
    }

    /*获取页面信息*/
    applyPayOrder(){
        Relay.Store.commitUpdate(
            new ApplyPayOrderMutation({
                orderId:this.orderId,
                orderMoney: this.state.orderMoney,
            }),
            {
                onFailure: () => {
                    message.error("请求失败")
                },
                onSuccess: (response) => {
                    let data = response.applyPayOrder.data;
                    if (data.errorCode === "0") {
                        this.setState({
                            remainOrderMoney:data.remainOrderMoney==null?"0.00":parseFloat(data.remainOrderMoney).toFixed(2),
                            cashMoney: data.cashMoney==null?"0.00":parseFloat(data.cashMoney).toFixed(2),
                            debtOrderMoney:data.debtOrderMoney==null?"0.00":parseFloat(data.debtOrderMoney).toFixed(2),
                            orderMoney:data.orderMoney==null?"0.00":parseFloat(data.orderMoney).toFixed(2),
                            ordermoney:data.orderMoney==null?"0.00":parseFloat(data.orderMoney).toFixed(2),
                            orderremain: data.remainOrderMoney==null?"0.00":parseFloat(data.remainOrderMoney).toFixed(2),
                            accountremain:data.cashMoney==null?"0.00":parseFloat(data.cashMoney).toFixed(2),
                            partBName:data.partBName==null?"":data.partBName,
                            partBUserName:data.partBUserName==null?"":data.partBUserName,
                            partBPhone:data.partBPhone==null?"":data.partBPhone,
                            canLoanMoney:data.loanInfoDomain == null ? '0.00' : data.loanInfoDomain.canLoanMoney,
                            dayRate:data.loanInfoDomain == null ? '0.00' : data.loanInfoDomain.dayRate
                        });
                    } else {
                        this.setState({
                            hint: data.value,
                        });
                        this.showError("请求支付失败",data.value);
                        hashHistory.push('/orderpaymentlist');//回到上个页面
                    }
                }

            }
        );
    }


    /*数字千分制*/
    doubleFormat(obj){
        if(!obj){
            return obj;
        }else{
            return parseFloat(obj).toLocaleString();
        }
    }

    //
    changeAccount(e){
        this.setState({
          btnLoading: false
        })
        const { orderremain, accountremain, hadPayWayAccount, payWayLoan } = this.state
        let inputaccount = e.target.value;
        let regular = /^[0-9]+\.?[0-9]{0,2}$/
        if(!regular.test(inputaccount) && inputaccount != ''){
            return
        } else if(inputaccount.length > 10) {
            return
        } else {
          this.setState({
              inputaccount: inputaccount,
              hadPayWayOrder: '0.00',
              hadPayWayAccount:  '0.00',
              hadPayWayLoan: '0.00'
          },()=>{
              this.updateInfo()
          });
        }

        if (inputaccount == '' || inputaccount == 0) {  //如果输入金额为空或者为0 三个付款方式清 0
            this.setState({
                hadPayWayOrder: '0.00',
                hadPayWayAccount:  '0.00',
                hadPayWayLoan: '0.00'
            })
        }
    }

    updateInfo() {
      const { inputaccount, orderremain, accountremain, hadPayWayAccount, payWayLoan, canLoanMoney } = this.state
      let temp = inputaccount;
      if(Number(inputaccount) > Number(orderremain)) {
        temp = Number(inputaccount) - Number(orderremain);
        this.setState({
          hadPayWayOrder: orderremain
        })
      } else {
        temp = 0
        this.setState({
          hadPayWayOrder: inputaccount
        })
      }

      if (Number(temp) > 0 && Number(temp) > Number(accountremain)) {
        temp = Number(temp) - Number(accountremain);
        this.setState({
          hadPayWayAccount: accountremain
        })
      } else {
        this.setState({
          hadPayWayAccount: temp
        });
        temp = 0;
      }

      if (Number(temp) > 0) {

        if (payWayLoan == 1) {
          this.setState({
            hadPayWayLoan: temp
          })
          if (temp > canLoanMoney) {
            //置灰
            this.setState({
              flag: 0
            })
          } else {
            //变蓝色
            this.setState({
              flag: 1
            })
          }
        } else {
          //置灰
          this.setState({
            hadPayWayLoan: '0.00',
            flag: 0
          })
        }
      } else {
        this.setState({
          hadPayWayLoan: '0.00',
          flag: 1
        })
        //按钮变蓝色
      }


    }
    /*点击支付*/
    payment(){
        let inputaccount = this.state.inputaccount
        message.config({
          top: 20,
          duration: 1.5,
        });
        if (Number(inputaccount) > Number(this.state.debtOrderMoney)) {
            message.info('付款金额不可超过尚未付款金额')
            return
        }
        if (inputaccount == null || inputaccount == '') {
            message.info('请输入支付金额')
            return
        }
        this.payOrder()
    }

    /*支付*/
    payOrder(){
      this.setState({btnLoading: true})
        Relay.Store.commitUpdate(
            new PayOrderMutation({
                orderId:this.orderId,
                payment: this.state.inputaccount,
                payWayOrder: 1,
                payWayLoan: this.state.payWayLoan,
                payWayAccount: 1
            }),
            {
                onFailure: () => {
                    message.error("请求失败")
                },
                onSuccess: (response) => {
                    let data = response.payOrder.data;
                    if (data.errorCode === "0") {
                        this.setState({
                          btnLoading: false,
                        })
                        hashHistory.push('/orderpaymentlist')
                    } else {
                        message.info(data.value)
                    }
                }
            }
        );
    }

    checkedClick(type, e) {
        const { inputaccount, orderremain, accountremain, payWayLoan } = this.state
        if (type == 'payWayLoan') {
          if (e.target.checked) {
              this.setState({
                  payWayLoan: 1
              },()=>{
                this.updateInfo()
              })
          } else {
            this.setState({
              hadPayWayLoan: '0.00',
              payWayLoan: '0.00'
            },()=>{
              this.updateInfo()
            })
          }
        }
    }

    render(){
        return (
            <div className="payment_pro_bg">
                <div className="payment_pro_box" >
                    <div className="payment_pro_info">
                        <div className="payment_pro_payInfo">
                            <p className="payment_pro_p">
                                <span className="payment_pro_span">订 单 号：</span>
                                <span className="payment_pro_span">{this.orderId}</span>
                            </p>
                            <p className="payment_pro_p">
                                <span className="payment_pro_span">收 款 方：</span>
                                <span className="payment_pro_span">{this.state.partBName}</span>
                            </p>
                            <p className="payment_pro_p">
                                <span className="payment_pro_span">订单金额：</span>
                                <span className="payment_pro_orderspan">￥{this.state.ordermoney=="NaN"?"0":this.state.ordermoney}</span>
                            </p>
                        </div>
                        <div className="payment_pro_ordermoney" style={{paddingTop: '73px'}}>
                            <p className="payment_pro_p">
                                <span className="payment_pro_span">尚未付款：</span>
                                <span className="payment_pro_orderspan1">￥{this.state.debtOrderMoney=="NaN"?"0":this.state.debtOrderMoney}</span>
                            </p>
                        </div>
                    </div>
                    <div className="payment_pro_payment">
                        <div className="payment_loan_set_searchInp">
                            <span className="payment_loan_set_searchInp_sp"><a className="payment_red">* </a>付款金额：</span>
                            <input value={this.state.inputaccount} onChange={this.changeAccount} type="text"/>
                        </div>
                        <span className="payment_loan_set_searchInp_sp">元</span>
                        {
                            //<p className="payment_red clear">请填写付款金额</p>
                        }
                    </div>
                    <div className="payment_pro_orderinfo">
                        {
                          this.entype != 1 ? (
                            <p className='payment_pro_infop'>
                                <Checkbox defaultChecked disabled checked={true}></Checkbox>
                                <span className="payment_pro_ordername">客户货款</span>
                                <span className="payment_pro_infospan">当前余额：{this.state.orderremain=="NaN"?"0":Util.doubleFormat(this.state.orderremain)}元</span>
                                <span className="payment_pro_infoR payment_pro_infospan">支付<a>{this.state.hadPayWayOrder ? Number(this.state.hadPayWayOrder).toFixed(2) : '0.00'}</a>元</span>
                            </p>
                          ) : null
                        }
                        <p className='payment_pro_infop'>
                            <Checkbox defaultChecked disabled checked={true}></Checkbox>
                            <span className="payment_pro_ordername">企业账户</span>
                            <span className="payment_pro_infospan">当前余额：{this.state.accountremain=="NaN"?"0":Util.doubleFormat(this.state.accountremain)}元</span>
                            <span className="payment_pro_infoR payment_pro_infospan">支付<a>{ this.state.hadPayWayAccount ? Number(this.state.hadPayWayAccount).toFixed(2) : '0.00'}</a>元</span>
                        </p>
                        <p className='payment_pro_infop' >
                            <Checkbox onChange={this.checkedClick.bind(this,'payWayLoan')}></Checkbox>
                            <span className="payment_pro_ordername">贷&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;款</span>
                            <span className="payment_pro_infospan">可贷额度：{this.state.canLoanMoney == 'NaN' ? '0': Util.doubleFormat(this.state.canLoanMoney)} 元</span>
                            <span className="payment_pro_infospan">贷款日利率：{this.state.dayRate}% </span>
                            <span className="payment_pro_infoR payment_pro_infospan">贷款支付<a>{this.state.hadPayWayLoan ? Number(this.state.hadPayWayLoan).toFixed(2) : '0.00'}</a>元</span>
                        </p>
                    </div>
                    {/*按钮*/}
                    <div className="payment_pro_buttonBox clear">
                      {
                        this.state.flag ==  1 ? (
                          <Button type="primary" loading={this.state.btnLoading} onClick={this.payment.bind(this)} key={ReactKey.key} disabled={this.state.btnLoading}> 立即支付 </Button>
                          ) : (
                          <p style={{cursor: 'no-drop'}} className="payment_pro_buttonBox_disn" key={ReactKey.key} > 立即支付 </p>
                        )
                      }
                    </div>
                </div>
            </div>
        )
    }
}
